#!/bin/sh

. /usr/share/common

if [ -z "$wireguard_address" ]; then
	echo_error "No WireGuard IP address configured"
	exit 1
fi

WIREGUARD_INTERFACE="wg0"
RESOLV_BAK="${RESOLV_WORKING_FILE}.bak"

start() {
	echo_title "Starting WireGuard"

	# "force" is for testing, to start WireGuard on demand without having it enabled at boot
	# "start" is for the normal boot process

	if [ "true" != "$wireguard_enabled" ] && [ "force" != "$1" ]; then
		echo_error "WireGuard disabled"
		exit 1
	fi

	if ip link show $WIREGUARD_INTERFACE 2>&1 | grep -q 'UP'; then
		echo_error "WireGuard interface $WIREGUARD_INTERFACE already up"
		exit 1
	fi

	echo_info "Create WireGuard network interface"
	ip link add dev $WIREGUARD_INTERFACE type wireguard

	echo_info "Create WireGuard configuration"
	tmp_file=$(mktemp -u)
	{
		echo '[Interface]'
		echo "PrivateKey=$wireguard_privkey"
		[ -n "$wireguard_port" ] && echo "ListenPort=$wireguard_port"
		echo '[Peer]'
		echo "Endpoint=$wireguard_endpoint"
		echo "PublicKey=$wireguard_peerpub"
		[ -n "$wireguard_peerpsk" ] && echo "PresharedKey=$wireguard_peerpsk"
		[ -n "$wireguard_allowed" ] && echo "AllowedIPs=$wireguard_allowed"
		[ -n "$wireguard_keepalive" ] && echo "PersistentKeepalive=$wireguard_keepalive"
	} >> "$tmp_file"

	echo_info "Apply WireGuard configuration"
	wg setconf "$WIREGUARD_INTERFACE" "$tmp_file"

	echo_info "Clean up"
	rm "$tmp_file"

	echo_info "Assign IP address to WireGuard interface"
	ip address add $wireguard_address dev $WIREGUARD_INTERFACE

	if [ -n "$wireguard_mtu" ]; then
		link_mtu="mtu $wireguard_mtu"
	fi

	echo_info "Start WireGuard interface"
	ip link set $link_mtu up dev $WIREGUARD_INTERFACE

	if [ -n "$wireguard_dns" ] ; then
		echo_info "Create custom resolver configuration"
		tmp_file=$(mktemp)
		grep -v nameserver $RESOLV_WORKING_FILE >> "$tmp_file"
		for x in $(echo $wireguard_dns | tr "," " ") ; do
			echo "nameserver $x" >> "$tmp_file"
		done

		echo_info "Back up existing resolver configuration"
		mv "$RESOLV_WORKING_FILE" "$RESOLV_BAK"

		echo_info "Set up custom resolver configuration"
		mv "$tmp_file" "$RESOLV_WORKING_FILE"
	fi

	for r in $(echo "$wireguard_allowed" | tr "," " ") ; do
		echo_info "Add routing to $r"
		ip route add $r dev $WIREGUARD_INTERFACE
	done
}

stop() {
	echo_title "Stopping WireGuard"

	for r in $(ip route | awk '/dev wg/{print $1}') ; do
		echo_info "Remove routing to $r"
		route del $r dev $WIREGUARD_INTERFACE
	done

	echo_info "Stop WireGuard interface"
	ip link set down $WIREGUARD_INTERFACE

	echo_info "Remove WireGuard interface"
	ip address del $wireguard_address dev $WIREGUARD_INTERFACE

	if [ -s "$RESOLV_BAK" ]; then
		echo_info "Restore original resolver configuration"
		mv "$RESOLV_BAK" "$RESOLV_WORKING_FILE"
	fi
}

case "$1" in
	force)
		start
		;;
	start)
		start
		;;
	stop)
		stop
		;;
	restart)
		stop
		start
		;;
	*)
		echo "Usage: $0 {force|start|stop|restart}"
		exit 1
		;;
esac

exit 0
